<route>
{
  "meta":{
    "title":"升级通知详情",
    "localism": "sys.upgrade_notification_details"
  }
}
</route>
<template>
  <div>
    <el-button
      icon="el-icon-back"
      type="primary"
      @click="$router.replace({ path: '/messageCenter/escalate' })"
    >
      {{$t('sys.return')}}
    </el-button>
    <div class="mt10" style="width: 50%; margin: 0 auto">
      <el-form :model="form" ref="form" label-width="130px">
        <el-form-item :label="$t('sys.upgrade_notification_CODE')" prop="升级通知CODE">
          <el-input
            v-model="form.code"
            :disabled="!!id || !canEdit"
            :maxlength="128"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          :label="$t('sys.type')"
          prop="type"
          :rules="[
            { required: true, message: $t('sys.type_not_null'), trigger: 'change' },
            { max: 128, message: $t('sys.type_maxlength_128') }
          ]"
        >
          <template
            slot="label"
          >{{$t('sys.upgrade_notification_type')}}
            <el-tooltip
              popper-class="custom-popper"
              :content="$t('sys.upgrade_notification_type_create_maxlength_128')"
              placement="top"
            >
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <el-select
            v-model="form.type"
            filterable
            :disabled="VUE_APP_USER === 'APP'"
            allow-create
            style="width: 100%"
            :placeholder="$t('sys.select_or_enter_to_new_type')"
          >
            <el-option
              v-for="(t, index) in types"
              :key="index"
              :value="t"
              :label="t"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('sys.description')" prop="description">
          <el-input
            type="textarea"
            :disabled="!canEdit || VUE_APP_USER === 'APP'"
            v-model="form.description"
            show-word-limit
            :maxlength="200"
          />
        </el-form-item>
        <el-form-item :label="$t('sys.upgrade_level')">
          <el-button
            :disabled="!canEdit"
            type="primary"
            size="small"
            style="margin-bottom: 36px"
            @click="onClickAddLevel"
          >{{$t('sys.add')}}</el-button
          >
        </el-form-item>
        <el-timeline style="margin-left: 100px">
          <el-timeline-item
            v-for="(item, index) in fullLevelList"
            :key="item.tempId"
            :icon="item.isTime ? 'el-icon-time' : ''"
            color="#1890ff"
          >
            <template v-if="item.isTime">
              <span v-if="item.intervalTime" style="margin-right: 8px">{{
                formatSeconds(item.intervalTime * 60)
              }}</span>
              <i
                v-if="item.intervalTime"
                class="el-icon-delete icon-btn-error"
                style="margin-right: 24px"
                @click="onDeleteInterval(item.tempId)"
              ></i>
              <span
                class="icon-btn"
                v-if="!item.intervalTime"
                @click="$refs.timeForm.show({ tempId: item.tempId })"
              >{{$t('sys.add')}}</span
              >
            </template>
            <template v-else>
              <div>
                <span style="margin-right: 8px">{{
                  `第${noToChinese(parseInt(index / 2) + 1)}层`
                }}</span>
                <i
                  v-if="fullLevelList.length > 1"
                  class="el-icon-delete icon-btn-error"
                  style="margin-right: 24px"
                  @click="onDeleteLevel(item.tempId)"
                ></i>
                <template v-for="r in item.receiverList">
                  <el-tooltip
                    v-if="r.name.length > 20"
                    :key="r.id + '_' + r.isOrg"
                    :title="r.name"
                  >
                    <el-tag
                      type="info"
                      style="margin-right: 8px"
                      :key="r.id + '_' + r.isOrg"
                      :closable="canEdit"
                      @close="
                        (e) =>
                          onRemoveReceiver(e, item.tempId, r.id + '_' + r.isOrg)
                      "
                    >
                      {{ `${r.name.slice(0, 20)}...` }}
                    </el-tag>
                  </el-tooltip>
                  <el-tag
                    v-else
                    type="info"
                    style="margin-right: 8px"
                    :key="r.id + '_' + r.isOrg"
                    :closable="canEdit"
                    @close="
                      (e) =>
                        onRemoveReceiver(e, item.tempId, r.id + '_' + r.isOrg)
                    "
                  >
                    {{ r.name }}
                  </el-tag>
                </template>
                <i
                  class="el-icon-plus icon-btn"
                  @click="onAddReceiver(item)"
                ></i>
              </div>
            </template>
          </el-timeline-item>
        </el-timeline>

        <el-form-item :label="$t('sys.loop')">
          <el-input-number
            :disabled="!canEdit"
            v-model="cycle"
            :min="1"
            :max="100"
            :precision="0"
            @blur="onBlurCycle"
            style="margin-right: 8px"
          />
          <span style="margin-right: 24px">{{$t('sys.times')}}</span>
          <span v-if="cycle > 1">
            <el-tooltip placement="top">
              <template slot="content">
                <span>{{$t('sys.cycle_interval')}}</span>
              </template>
              <i
                class="icon-btn el-icon-time mr5"
                :disabled="!canEdit"
                @click="$refs.cycleForm.show({ intervalTime })"
              ></i>
            </el-tooltip>

            <span>{{ formatSeconds(intervalTime * 60) }}</span>
          </span>
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button
            :loading="confirmLoading"
            style="margin-right: 20px"
            @click="handleSubmit"
            type="primary"
          >{{$t('sys.submit')}}</el-button
          >
          <el-button @click="handleReset">{{$t('sys.reset')}}</el-button>
        </el-form-item>
      </el-form>
      <time-form ref="timeForm" @ok="onSubmitAddLevelInterval" />
      <time-form ref="cycleForm" @ok="onSubmitAddCycleInterval" />
      <select-modal
        ref="selectModalMember"
        :title="$t('sys.select_recipient')"
        childDisable
        :autoClose="false"
        :treeData="filteredOrgTree"
        :showCheckbox="true"
        :treeCheckStrictly="true"
        :disabledNodeKeys="selectedOrgTreeKeys"
        :disabledItemKeys="selectedMemberKeys.map((item) => item.id)"
        :treeNodeChange="loadMemberUserData"
        :defaultSelectedTreeKeys="selectedOrgTreeKeys"
        @ok="onSubmitReceiver"
      />
    </div>
  </div>
</template>

<script>

import { cloneDeep } from 'lodash'
import {
  noToChinese,
  uuidv4,
  formatSeconds,
  arrayToTree,
  breadFirstTree
} from '@/utils/util'
import SelectModal from '@/components/SelectModal'

import TimeForm from './__components__/TimeForm'

import { getMsgUpgradenoticeTypes,postMsgUpgradenotice,putMsgUpgradenotice,getMsgUpgradenoticeDetails } from '@/apis/paas/UpgradeNoticeController.js'
import { getHmuserPageListwithpermission } from '@/apis/paas/HmUserController.js'
import { getHmorgListwithpermission } from '@/apis/paas/HmOrgController.js'
export default {
  name: 'EscalateDetail',
  components: {
    SelectModal,
    TimeForm
  },
  data () {
    return {
      VUE_APP_USER: process.env.VUE_APP_USER,
      loading: false,
      id: 0,
      types: [],
      form: {},
      confirmLoading: false,
      fullLevelList: [],
      varList: [],
      orgTree: [], // 原始部门树
      selectedMemberKeys: [], // 已选人员ids
      selectedOrgTreeKeys: [], // 已选部门树ids
      filteredOrgTree: [], // 可选部门树
      cycle: 1,
      intervalTime: 30,
      selectedLevel: {},
      canEdit: true
    }
  },
  computed: {},
  created () {
    const id = this.$route.query.id
    this.id = id
    this.init()
  },
  methods: {
    formatSeconds,
    noToChinese,
    init () {
      this.getTypeList()
      this.getOrgTree()
      if (this.id) {
        this.initEscalate(this.id)
      } else {
        this.fullLevelList = [
          {
            tempId: uuidv4(),
            level: 0,
            receiverList: [],
            isTime: false
          }
        ]
      }
    },
    getTypeList () {
      getMsgUpgradenoticeTypes().then((res) => {
        this.types = res || []
      })
    },

    getOrgTree () {
      getHmorgListwithpermission().then((res) => {
        this.orgTree = arrayToTree(res)
        // if (this.expandedOrg.length === 0 && this.orgTree.length > 0) {
        //   this.expandedOrg = [this.orgTree[0].id]
        // }
        // if (!this.currentOrg && this.orgTree.length > 0) {
        //   this.currentOrg = this.orgTree[0].id
        //   this.$nextTick(() => {
        //     this.$refs.tree.setCurrentKey(this.orgTree[0].id)
        //     this.handleOrgClick(this.orgTree[0])
        //   })
        // }
      })
    },
    loadMemberUserData (org) {
      return getHmuserPageListwithpermission({
        pageSize: 100000,
        pageNo: 1,
        orgIds: org.id,
        status: 1
      }).then((res) => {
        const data = res.data
        data.forEach((item) => {
          item.label = `[${item.jobNumber}]${item.name}`
          item.value = item.id
          if (this.selectedMemberKeys.includes(item.id)) {
            item.disabled = true
          }
        })
        return data
      })
    },

    initEscalate (id) {
      this.loading = true
      getMsgUpgradenoticeDetails({ id })
        .then((res) => {
          const { upgradeNotice, upgradeNoticeDetails } = res
          if (upgradeNotice) {
            const {
              code,
              type,
              description,
              cycle,
              intervalTime,
              ...otherConfig
            } = upgradeNotice
            this.templateConfig = otherConfig
            this.cycle = cycle
            this.intervalTime = intervalTime
            this.$nextTick(() => {
              this.form = { code, type, description: description || '' }
            })
          }
          this.fullLevelList = this.genFullLevelList(upgradeNoticeDetails)
        })
        .finally(() => {
          this.loading = false
        })
    },

    genFullLevelList (arr) {
      const fullLevelList = []
      for (let i = 0; i < arr.length; i++) {
        if (i !== 0) {
          fullLevelList.push({
            tempId: uuidv4(),
            intervalTime: arr[i].intervalTime,
            isTime: true
          })
        }
        const receiverList = []
        const unionIdArr = arr[i].unionIds.split(',')
        const unionNameArr = arr[i].unionNames.split(',')
        const isOrgArr = arr[i].types.split(',')
        for (let j = 0; j < unionIdArr.length; j++) {
          const tempArr = unionIdArr[j].split('_')
          tempArr.shift()
          receiverList.push({
            id: tempArr.length > 1 ? tempArr.join('_') : parseInt(tempArr[0]),
            name: unionNameArr[j],
            isOrg: parseInt(isOrgArr[j])
          })
        }
        fullLevelList.push({
          id: arr[i].id,
          level: i,
          receiverList,
          isTime: false,
          tempId: uuidv4()
        })
      }
      return fullLevelList
    },
    onClickAddLevel () {
      const level = Math.floor((this.fullLevelList.length + 1) / 2)
      this.fullLevelList = this.fullLevelList.concat([
        {
          tempId: uuidv4(),
          intervalTime: 0,
          isTime: true
        },
        {
          tempId: uuidv4(),
          level,
          receiverList: [],
          isTime: false
        }
      ])
    },

    onDeleteLevel (tempId) {
      const index = this.fullLevelList.findIndex((ele) => ele.tempId === tempId)
      if (index === 0) {
        this.fullLevelList = this.fullLevelList.filter((ele, idx) => {
          return idx !== index && idx !== index + 1
        })
      } else {
        this.fullLevelList = this.fullLevelList.filter((ele, idx) => {
          return idx !== index && idx !== index - 1
        })
      }
    },

    onDeleteInterval (tempId) {
      this.fullLevelList = this.fullLevelList.map((ele) => {
        if (ele.tempId === tempId) {
          ele.intervalTime = 0
        }
        return ele
      })
    },

    onAddReceiver (item) {
      this.selectedLevel = item
      const selectedOrgIds = []
      const selectedMemberKeys = []
      for (const obj of item.receiverList) {
        if (obj.isOrg === 1) {
          selectedOrgIds.push(obj.id)
        } else if (obj.isOrg === 2) {
          selectedOrgIds.push(parseInt(obj.id.split('_')[0]))
        } else if (obj.isOrg === 0) {
          selectedMemberKeys.push(obj.id)
        }
      }
      const tree = cloneDeep(this.orgTree)
      breadFirstTree(
        tree,
        (jn) => {
          if (selectedOrgIds.includes(jn.id)) {
            jn.disabled = true
            breadFirstTree(
              jn.children,
              (el) => {
                el.disabled = true
                return true
              },
              'children'
            )
          }
          return true
        },
        'children'
      )
      this.selectedOrgTreeKeys = selectedOrgIds
      this.selectedMemberKeys = selectedMemberKeys
      this.filteredOrgTree = tree
      this.$refs.selectModalMember.open()
    },

    onSubmitReceiver (values) {
      const userList = values.item.map((ele) => {
        const rt = {
          id: ele.id,
          name: ele.name,
          isOrg: 0
        }
        return rt
      })
      const orgList = values.node.map((ele) => {
        const rt = {
          id: ele.id,
          name: ele.name,
          isOrg: 1
        }
        if (ele.extra) {
          rt.id = `${ele.id}_${ele.extra}`
          rt.name = `${ele.name}_${ele.extra}`
          rt.isOrg = 2
        }
        return rt
      })
      this.fullLevelList = this.fullLevelList.map((ele) => {
        if (ele.tempId === this.selectedLevel.tempId) {
          ele.receiverList = ele.receiverList.concat(userList).concat(orgList)
        }
        return ele
      })
      this.$refs.selectModalMember.close()
    },

    /**
     * 此处id其实是id_isOrg结构，为了规避人员id和组织id重复
     */
    onRemoveReceiver (e, levelId, id) {
      e.preventDefault()
      this.fullLevelList = this.fullLevelList.map((ele) => {
        if (ele.tempId === levelId) {
          ele.receiverList = ele.receiverList.filter(
            (r) => r.id + '_' + r.isOrg !== id
          )
        }
        return ele
      })
    },

    onSubmitAddLevelInterval (values) {
      const { tempId, intervalTime } = values
      this.fullLevelList = this.fullLevelList.map((ele) => {
        if (ele.tempId === tempId) {
          ele.intervalTime = intervalTime
        }
        return ele
      })
    },

    onBlurCycle (e) {
      if (!e.target.value) {
        this.cycle = 1
      }
    },

    onSubmitAddCycleInterval (values) {
      this.intervalTime = values.intervalTime
    },

    // 校验层级
    validateLevelList () {
      let valid = true
      for (let i = 0; i < this.fullLevelList.length; i++) {
        const item = this.fullLevelList[i]
        if (item.isTime) {
          if (!item.intervalTime) {
            this.$notify({
              title: this.$t('sys.error'),
              message: this.$t('sys.level_interval_not_null'),
              type: 'error'
            })
            valid = false
            break
          }
        } else {
          if (item.receiverList.length === 0) {
            this.$notify({
              title: this.$t('sys.error'),
              message: this.$t('sys.notification_receiver_not_null'),
              type: 'error'
            })
            valid = false
            break
          }
        }
      }
      return valid
    },

    convertToOriginList () {
      const rt = []
      for (let i = 0; i < this.fullLevelList.length; i += 2) {
        const item = this.fullLevelList[i]
        const obj = {
          id: item.id || 0,
          codeId: this.id,
          unionIds: item.receiverList
            .map((ele) => `${ele.isOrg}_${ele.id}`)
            .join(','),
          unionNames: item.receiverList.map((ele) => ele.name).join(','),
          types: item.receiverList.map((ele) => ele.isOrg).join(','),
          intervalTime: 0
        }
        rt.push(obj)
      }
      for (let i = 1; i < this.fullLevelList.length - 1; i += 2) {
        rt[parseInt(i / 2) + 1].intervalTime =
          this.fullLevelList[i].intervalTime
      }
      return rt
    },

    async handleSubmit () {
      if (this.validateLevelList()) {
        try {
          await this.$refs.form.validate()
          const { code, type, description } = this.form
          const model = {
            upgradeNotice: {
              id: this.id || null,
              code: code ? code.trim() : '',
              type,
              description: description ? description.trim() : '',
              cycle: this.cycle,
              intervalTime: this.intervalTime
            },
            upgradeNoticeDetails: this.convertToOriginList()
          }
          this.confirmLoading = true
          if (!this.id) {
            postMsgUpgradenotice(model)
              .then((res) => {
                this.$router.push({ path: '/messageCenter/escalate' })
              })
              .finally(() => {
                this.confirmLoading = false
              })
          } else {
            putMsgUpgradenotice(model)
              .then((res) => {
                this.$router.push({ path: '/messageCenter/escalate' })
              })
              .finally(() => {
                this.confirmLoading = false
              })
          }
        } catch (error) {}
      }
    },

    handleReset () {
      this.init()
    }
  }
}
</script>

<style>
.icon-btn {
  color: #1890ff;
  cursor: pointer;
}
.icon-btn-error {
  color: #ec2234;
  cursor: pointer;
}
</style>
